package com.sunrise.xdoc.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import com.sunrise.xdoc.dto.LoaiSanPhamDTO;
import com.sunrise.xdoc.entity.catalog.LoaiSanPham;
import com.sunrise.xdoc.entity.catalog.SanPham;
import com.sunrise.xdoc.entity.order.DinhMuc;
import com.sunrise.xdoc.service.AbstractService;
import com.sunrise.xdoc.service.ICatalogService;

@Service("catalogService")
public class CatalogService extends AbstractService implements ICatalogService {
	private static final long serialVersionUID = 3823911982194214619L;

	@Override
	public List<LoaiSanPhamDTO> getLoaiSanPhamOfSanPhamDuocBan() {
		List<LoaiSanPham> loaiSanPhams = getDaoHelper().getDao(LoaiSanPham.class).loadAll();
		DetachedCriteria dcDinhMuc = getDaoHelper().getDao(DinhMuc.class).getDetachedCriteria();
		dcDinhMuc.add(Restrictions.gt("dinhMucBan", 0));
		dcDinhMuc.createCriteria("sanPham").add(Restrictions.eq("active", true));
		List<DinhMuc> dinhMucs = getDaoHelper().getDao(DinhMuc.class).findByCriteria(dcDinhMuc);
		return groupDinhMuc(loaiSanPhams, dinhMucs);
	}

	@Override
	public List<LoaiSanPham> getAllLoaiSanPhams() {
		return getDaoHelper().getDao(LoaiSanPham.class).loadAll();
	}

	/**
	 * Nhóm định mức theo loại sản phẩm.
	 * 
	 * @param loaiSanPhams
	 * @param dinhMucs
	 * @return
	 */
	private List<LoaiSanPhamDTO> groupDinhMuc(List<LoaiSanPham> loaiSanPhams, List<DinhMuc> dinhMucs) {
		List<LoaiSanPhamDTO> loaiSpDTOs = new ArrayList<>(loaiSanPhams.size());
		for (LoaiSanPham lsp : loaiSanPhams) {
			LoaiSanPhamDTO loaiSanPhamDTO = new LoaiSanPhamDTO();
			loaiSanPhamDTO.setLoaiSanPham(lsp);
			for (DinhMuc dm : dinhMucs) {
				if (lsp.equals(dm.getSanPham().getLoaiSP())) {
					loaiSanPhamDTO.getDinhMucs().add(dm);
				}
			}
			if (loaiSanPhamDTO.getDinhMucs().size() != 0) {
				loaiSpDTOs.add(loaiSanPhamDTO);
			}
		}
		return loaiSpDTOs;
	}

	@Override
	public void activeSanPhams(List<Long> spIds, boolean active) {
		String query = "UPDATE SanPham s SET s.active=:active WHERE s.id IN (:spIds)";
		getDaoHelper().getDao(SanPham.class).getCurrentSession().createQuery(query).setParameter("active", active)
				.setParameterList("spIds", spIds).executeUpdate();
	}
}
